<template>
  <div
    class="todo-item"
    :class="{ completed: todo.completed }"
    @mouseenter="isHovered = true"
    @mouseleave="isHovered = false"
  >
    <div class="todo-checkbox" @click="toggleComplete">
      <div class="checkbox-inner" v-if="todo.completed">✓</div>
    </div>
    <!-- 正常模式显示待办内容，使用 white-space: pre-wrap 保留换行 -->
    <div v-if="!isEditing" class="todo-text" @dblclick="startEditing">{{ todo.content }}</div>
    <!-- 编辑模式显示文本框 -->
    <div v-else class="todo-edit-wrapper">
      <textarea
        class="todo-edit-input"
        v-model="editContent"
        ref="editInput"
        @keydown.enter.prevent="handleEnterKey"
        @keyup.esc="cancelEdit"
        @blur="cancelEdit"
        rows="1"
      ></textarea>
    </div>

    <!-- 编辑按钮 - 只有悬停时显示 -->
    <button v-if="isHovered" class="todo-edit-btn" @click="openEditModal">
      <svg
        viewBox="0 0 24 24"
        width="16"
        height="16"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
      >
        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
      </svg>
    </button>

    <!-- 拖动手柄 - 只有悬停时显示 -->
    <div v-if="isHovered" class="drag-handle" @mousedown="handleDragStart">
      <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
        <path
          d="M9 3h2v2H9V3zm0 4h2v2H9V7zm0 4h2v2H9v-2zm0 4h2v2H9v-2zm0 4h2v2H9v-2zM13 3h2v2h-2V3zm0 4h2v2h-2V7zm0 4h2v2h-2v-2zm0 4h2v2h-2v-2zm0 4h2v2h-2v-2z"
        />
      </svg>
    </div>

    <!-- 编辑分类弹窗 -->
    <div class="modal-overlay" v-if="showEditModal" @click="closeEditModal">
      <div class="modal-content" @click.stop>
        <h3 class="modal-title">编辑待办事项</h3>
        <div class="modal-body">
          <!-- 添加待办内容编辑区域 -->
          <div class="form-group">
            <label for="todoContent">待办内容</label>
            <textarea
              id="todoContent"
              class="todo-content-input"
              v-model="editModalContent"
              placeholder="输入待办内容..."
              rows="3"
            ></textarea>
          </div>

          <div class="form-group">
            <label>选择标签</label>
            <div class="category-select" @click.stop="toggleCategoryDropdown">
              <div class="selected-tags">
                <template v-if="selectedCategories.length > 0">
                  <div v-for="cat in selectedCategories" :key="cat.id" class="selected-tag">
                    <span class="tag-name">{{ cat.name }}</span>
                    <span class="tag-remove" @click.stop="removeSelectedCategory(cat)">×</span>
                  </div>
                </template>
                <span v-else class="placeholder">选择标签</span>
              </div>
              <div class="dropdown-icon">▼</div>

              <div class="category-dropdown" v-if="showCategoryDropdown">
                <div
                  v-for="category in categories"
                  :key="category.id"
                  class="category-item"
                  @click.stop="toggleCategory(category)"
                  :class="{ 'category-selected': isCategorySelected(category) }"
                >
                  <span class="checkbox">
                    <span v-if="isCategorySelected(category)" class="checkbox-inner">✓</span>
                  </span>
                  <span class="category-name">{{ category.name }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button
            class="confirm-btn"
            @click="saveCategories"
            :disabled="selectedCategories.length === 0"
          >
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch, onMounted, onUnmounted } from 'vue'
import { updateTodo } from '@/api/todo'
import { getAllLabels } from '@/api/label'

const props = defineProps({
  todo: {
    type: Object,
    required: true,
  },
})

const emit = defineEmits(['toggle', 'update', 'dragstart'])

// 悬停状态
const isHovered = ref(false)

// 获取待办项的ID（兼容不同的数据结构）
const getTodoId = (todo) => {
  return todo.todoItemId || todo.id
}

// 编辑相关状态
const isEditing = ref(false)
const editContent = ref('')
const editInput = ref(null)

// 编辑分类相关状态
const showEditModal = ref(false)
const showCategoryDropdown = ref(false)
const categories = ref([])
const selectedCategories = ref([])
const editModalContent = ref('')

// 切换完成状态
const toggleComplete = () => {
  emit('toggle', getTodoId(props.todo))
}

// 处理拖动开始
const handleDragStart = (event) => {
  // 找到父级的待办项元素
  const todoItem = event.target.closest('.todo-item')
  if (todoItem) {
    todoItem.draggable = true

    // 添加拖动开始事件监听
    const handleDragStartEvent = (dragEvent) => {
      dragEvent.dataTransfer.effectAllowed = 'move'
      dragEvent.dataTransfer.setData('text/plain', getTodoId(props.todo))
      todoItem.classList.add('dragging')

      // 通知父组件
      emit('dragstart', { event: dragEvent, todo: props.todo })
    }

    const handleDragEnd = () => {
      todoItem.draggable = false
      todoItem.classList.remove('dragging')
      todoItem.removeEventListener('dragstart', handleDragStartEvent)
      todoItem.removeEventListener('dragend', handleDragEnd)
    }

    todoItem.addEventListener('dragstart', handleDragStartEvent)
    todoItem.addEventListener('dragend', handleDragEnd)

    // 触发拖动
    const dragStartEvent = new DragEvent('dragstart', {
      bubbles: true,
      cancelable: true,
    })

    setTimeout(() => {
      todoItem.dispatchEvent(dragStartEvent)
    }, 0)
  }
}

// 开始编辑
const startEditing = () => {
  editContent.value = props.todo.content
  isEditing.value = true

  // 等待DOM更新后聚焦输入框并自动调整高度
  setTimeout(() => {
    if (editInput.value) {
      editInput.value.focus()
      editInput.value.select()
      // 自动调整文本框高度
      adjustTextareaHeight(editInput.value)
    }
  }, 0)
}

// 添加自动调整高度的函数
const adjustTextareaHeight = (element) => {
  element.style.height = 'auto'
  element.style.height = element.scrollHeight + 'px'
}

// 监听输入内容变化，自动调整高度
watch(editContent, () => {
  if (editInput.value) {
    adjustTextareaHeight(editInput.value)
  }
})

// 处理回车键
const handleEnterKey = (event) => {
  if (event.shiftKey) {
    // 如果按住了 shift 键，插入换行符
    const start = event.target.selectionStart
    const end = event.target.selectionEnd
    editContent.value =
      editContent.value.substring(0, start) + '\n' + editContent.value.substring(end)

    // 等待 DOM 更新后设置光标位置
    setTimeout(() => {
      event.target.selectionStart = event.target.selectionEnd = start + 1
      // 调整文本框高度
      adjustTextareaHeight(event.target)
    }, 0)
  } else {
    // 普通回车键，保存编辑
    saveEdit()
  }
}

// 保存编辑
const saveEdit = async () => {
  if (editContent.value.trim() === '') return

  try {
    // 调用更新API
    const result = await updateTodo({
      id: getTodoId(props.todo),
      isCompleted: props.todo.completed,
      labels: [props.todo.labelId],
      content: editContent.value,
    })

    if (result.success) {
      // 通知父组件更新
      emit('update', {
        id: getTodoId(props.todo),
        content: editContent.value,
      })

      // 退出编辑模式
      isEditing.value = false
    } else {
      console.error('更新待办失败:', result.msg)
    }
  } catch (error) {
    console.error('更新待办失败:', error)
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
}

// 打开编辑分类弹窗
const openEditModal = async () => {
  showEditModal.value = true

  // 获取所有标签
  await fetchAllLabels()

  // 设置当前选中的标签
  initSelectedCategories()

  // 设置当前待办内容
  editModalContent.value = props.todo.content
}

// 关闭编辑分类弹窗
const closeEditModal = () => {
  showEditModal.value = false
  showCategoryDropdown.value = false
}

// 获取所有标签
const fetchAllLabels = async () => {
  try {
    const result = await getAllLabels()
    if (result.success) {
      categories.value = result.data.map((label) => ({
        id: label.id,
        name: label.name,
        color: label.color || '#4361ee',
      }))
    } else {
      console.error('获取标签失败:', result.msg)
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 初始化已选标签
const initSelectedCategories = () => {
  selectedCategories.value = []

  // 获取当前待办项的分类
  if (props.todo.labelId) {
    const currentCategory = categories.value.find((cat) => cat.id === props.todo.labelId)
    if (currentCategory) {
      selectedCategories.value.push(currentCategory)
    }
  }
}

// 切换分类下拉菜单
const toggleCategoryDropdown = (event) => {
  event.stopPropagation()
  showCategoryDropdown.value = !showCategoryDropdown.value
}

// 检查分类是否已选中
const isCategorySelected = (category) => {
  return selectedCategories.value.some((cat) => cat.id === category.id)
}

// 切换分类选中状态
const toggleCategory = (category) => {
  if (isCategorySelected(category)) {
    // 如果已选中，移除
    removeSelectedCategory(category)
  } else {
    // 如果未选中，添加
    selectedCategories.value.push(category)
  }
}

// 移除已选分类
const removeSelectedCategory = (category) => {
  selectedCategories.value = selectedCategories.value.filter((cat) => cat.id !== category.id)
}

// 保存分类更改
const saveCategories = async () => {
  if (selectedCategories.value.length === 0 || !editModalContent.value.trim()) return

  try {
    // 获取所有选中分类的ID
    const labelIds = selectedCategories.value.map((cat) => cat.id)

    // 调用API更新待办
    const result = await updateTodo({
      id: getTodoId(props.todo),
      isCompleted: props.todo.completed,
      labels: labelIds,
      content: editModalContent.value.trim(),
    })

    if (result.success) {
      // 关闭弹窗
      closeEditModal()

      // 通知父组件刷新数据
      window.dispatchEvent(new Event('refresh-todo-list'))
    } else {
      console.error('更新待办失败:', result.msg)
    }
  } catch (error) {
    console.error('更新待办失败:', error)
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = () => {
  showCategoryDropdown.value = false
}

onMounted(() => {
  window.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  window.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;
  padding: 18px 20px;
  border-radius: 50px;
  margin-bottom: 12px;
  background-color: #f5f5f7;
  transition: all 0.2s;
  flex-shrink: 0;
  word-break: break-all;
  min-height: 58px;
}

.todo-item:last-child {
  margin-bottom: 10px;
}

.todo-item:hover {
  background-color: #e5e5ea;
}

.todo-item.completed .todo-text {
  text-decoration: line-through;
  color: #86868b;
}

.todo-checkbox {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 2px solid #4361ee;
  margin-right: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.checkbox-inner {
  color: white;
  font-size: 13px;
  font-weight: bold;
}

.todo-item.completed .todo-checkbox {
  background-color: #4361ee;
}

.todo-text {
  flex: 1;
  font-size: 15px;
  cursor: text;
  word-break: break-all;
  overflow-wrap: break-word;
  min-width: 0;
  white-space: pre-wrap;
  line-height: 1.5;
}

/* 添加一个底部虚线指示可编辑 */
.todo-text:hover::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 1px;
  border-bottom: 1px dashed #4361ee;
}

.todo-edit-wrapper {
  flex: 1;
  min-width: 0;
  position: relative;
}

.todo-edit-input {
  width: 100%;
  border: none;
  background: transparent;
  font-size: 15px;
  padding: 0;
  outline: none;
  border-bottom: 1px solid #4361ee;
  word-break: break-all;
  overflow-wrap: break-word;
  resize: none;
  min-height: 24px;
  height: auto;
  line-height: 1.5;
  font-family: inherit;
  white-space: pre-wrap;
}

/* 调整编辑状态下的item样式 */
.todo-item.editing {
  height: auto;
  min-height: 58px;
  align-items: flex-start;
  padding-top: 16px;
}

.todo-item.editing .todo-checkbox {
  margin-top: 2px; /* 稍微调整复选框位置 */
}

/* 拖动手柄样式 */
.drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: grab;
  color: #86868b;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.drag-handle:hover {
  color: #4361ee;
  background-color: rgba(67, 97, 238, 0.1);
}

.drag-handle:active {
  cursor: grabbing;
}

.todo-edit-btn {
  border-radius: 50%;
  background: none;
  border: none;
  cursor: pointer;
  color: #86868b;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  padding: 4px;
}

.todo-edit-btn:hover {
  color: #4361ee;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.modal-title {
  padding: 20px;
  border-bottom: 1px solid #f5f5f7;
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #f5f5f7;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background-color: #f5f5f7;
  color: #1d1d1f;
  border: none;
}

.cancel-btn:hover {
  background-color: #e5e5ea;
}

.confirm-btn {
  background-color: #4361ee;
  color: white;
  border: none;
}

.confirm-btn:hover {
  background-color: #3a56d4;
}

.confirm-btn:disabled {
  background-color: #d2d2d7;
  cursor: not-allowed;
}

/* 标签选择样式 */
.category-select {
  position: relative;
  padding: 12px 15px;
  border: 1px solid #d2d2d7;
  border-radius: 15px;
  font-size: 14px;
  margin-bottom: 15px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 45px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
  gap: 6px;
}

.selected-tag {
  display: flex;
  align-items: center;
  background-color: #f0f2ff;
  border-radius: 20px;
  padding: 4px 10px;
  font-size: 12px;
}

.tag-name {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag-remove {
  margin-left: 5px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  border-radius: 50%;
}

.tag-remove:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

.placeholder {
  color: #86868b;
}

.dropdown-icon {
  font-size: 10px;
  color: #86868b;
  margin-left: 8px;
}

.category-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background-color: #ffffff;
  border: 1px solid #d2d2d7;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
  margin-top: 5px;
}

.category-item {
  padding: 10px 15px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
}

.category-item:hover {
  background-color: #f5f5f7;
}

.category-selected {
  background-color: #f0f2ff;
}

.checkbox {
  width: 18px;
  height: 18px;
  border-radius: 4px;
  border: 1px solid #d2d2d7;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-selected .checkbox {
  background-color: #4361ee;
  border-color: #4361ee;
}

.checkbox-inner {
  color: white;
  font-size: 12px;
}

.category-name {
  flex: 1;
}

@media (max-width: 768px) {
  .modal-content {
    width: 90%;
    margin: 20px auto;
  }

  .todo-edit-btn,
  .drag-handle {
    opacity: 0.8; /* 在移动设备上总是显示按钮 */
    width: 20px;
    height: 20px;
  }

  .todo-item {
    padding: 10px;
    margin-bottom: 5px;
  }

  .todo-checkbox {
    margin-right: 5px;
  }

  .todo-text {
    font-size: 14px;
  }

  .todo-edit-btn {
    margin-right: 5px;
  }
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #86868b;
  font-weight: 500;
}

.todo-content-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #d2d2d7;
  border-radius: 12px;
  font-size: 14px;
  resize: vertical;
  min-height: 80px;
  transition: border-color 0.3s;
  line-height: 1.5;
  font-family: inherit;
}

.todo-content-input:focus {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}
</style>
